package com.bigone.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Created by yulongguang on 2016/11/12.
 */
public class JSONObjectSample {
    //创建JSONObject
    public static JSONObject createJSONObject(){
        JSONObject jsonObject=new JSONObject();//集合形式
        jsonObject.put("username","ylg");
        jsonObject.put("sex","男");
        jsonObject.put("QQ","888");
        return jsonObject;
    }

    public static void main(String[] args) {
        JSONObject jsonObject=JSONObjectSample.createJSONObject();
        //输出jsonObject对象
        System.out.println("jsonObject==>"+jsonObject);

        //判读输出对象的类型
        boolean isArrery=jsonObject.isArray();
        boolean isEmpty=jsonObject.isEmpty();
        boolean isNullObject=jsonObject.isNullObject();
        System.out.println("isArrery==>"+isArrery+"isEmpty==>"+isEmpty+"isNullObject==>"+isNullObject);
        jsonObject.element("address","广州天河");
        System.out.println("添加后的属性"+jsonObject);

        //返回一个JSONArray对象
        JSONArray jsonArray=new JSONArray();//数组
        jsonArray.add(0,"this is jsonArray value");
        jsonArray.add(1,"another is jsonArray value ");
        jsonObject.element("jsonArray",jsonArray);
        System.out.println("jsonArray==>"+jsonArray);
        JSONArray array=jsonObject.getJSONArray("jsonArray");
        System.out.println("返回一个JSONArray对象:"+array);
        System.out.println("结果集="+jsonObject);

        String username=jsonObject.getString("username");
        System.out.println("username=>"+username);

        //把字符串转换成JSONObject
        String temp=jsonObject.toString();
        JSONObject object=JSONObject.fromObject(temp);
        System.out.println("object==>"+object);
        //转换后根据key返回值
        System.out.println("qq="+object.get("QQ"));
    }

}
